package com.abl.core.common.web;

import com.abl.core.domain.project.MSG;
import com.abl.core.domain.project.SRS;
import com.abl.core.domain.project.ServiceException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@Configuration
@RestControllerAdvice
public class ExceptionHandler {

    /**
     * 全局异常处理
     */
    @org.springframework.web.bind.annotation.ExceptionHandler(value = ServiceException.class)
    public SRS<Object> serviceExceptionHandler(ServiceException ex) {
        log.error("【ServiceException】", ex);
        return ex.getResponse();
    }

    //Token校验失败
    @org.springframework.web.bind.annotation.ExceptionHandler(value = JWTVerificationException.class)
    public SRS<Object> jwtVerExceptionHandler(JWTVerificationException ex) {
        log.error("【JWTVerificationException】", ex);
        return SRS.byError(MSG.ER_410);
    }

    //Token已失效
    @org.springframework.web.bind.annotation.ExceptionHandler(value = TokenExpiredException.class)
    public SRS<Object> jwtExpiredExceptionHandler(TokenExpiredException ex) {
        log.error("【TokenExpiredException】", ex);
        return SRS.byError(MSG.ER_410);
    }

    //接收参数转换异常
    @org.springframework.web.bind.annotation.ExceptionHandler(value = HttpMessageNotReadableException.class)
    public SRS<Object> httpMessageExceptionHandler(HttpMessageNotReadableException ex) {
        log.error("【HttpMessageNotReadableException】", ex);
        return SRS.byError(MSG.PARAM_ER);
    }

    //接收参数转换异常
    @org.springframework.web.bind.annotation.ExceptionHandler(value = MissingServletRequestParameterException.class)
    public SRS<Object> paramExceptionHandler(MissingServletRequestParameterException ex) {
        log.error("【MissingServletRequestParameterException】", ex);
        return SRS.byError(MSG.PARAM_ER);
    }

    //不明异常
    @org.springframework.web.bind.annotation.ExceptionHandler(value = Exception.class)
    public SRS<Object> exceptionHandler(Throwable ex) {
        log.error("【Exception】", ex);
        return SRS.byError(ex.getMessage());
    }

}
